import http from '../services/http/index'
import routes from '../routes/index'
import utils from '../utils/index'
import Emitter from '../utils/Emitter'
import {
  LAST_LOGIN,
  TOKEN
} from '../constants/storage'
import {
  USER_INFO
} from '../constants/user'
import {
  user as userStore
} from '../store/index';
import Toast from "../pages/components/toast/toast.js";

// 登录成功事件
export const EVENT_LOGIN = 'loginSuccess'

export default {
  /**
   * _data
   * @private
   */
  _data: {
    [TOKEN]: '',
  },

  eventEmitter: new Emitter(),

  /**
   * 检测是否登录状态
   * @returns {boolean}
   */
  getIsLogin() {
    this._data[TOKEN] = wx.getStorageSync(TOKEN)
    const lastLogin = +wx.getStorageSync(LAST_LOGIN) || 0
    // 登录信息有效时间为 24h
    const now = Date.now(),
      hours = 24,
      mins = 60,
      secs = 60,
      ms = 1000

    return !!this._data[TOKEN] && (now - lastLogin < hours * mins < secs < ms)
  },

  /**
   * 是否已授权
   * @returns {Promise}
   */
  getIsAuthAsync() {
    const self = this
    return new Promise((resolve, reject) => {
      wx.getSetting({
        success(res) {
          if (res.authSetting['scope.userInfo']) {
            resolve('scope.userInfo:ok')
          } else {
            self.clearLoginStatus()
            reject('scope.userInfo:fail')
          }
        },
      })
    })
  },

  /**
   * 获取用户信息
   * @returns {Promise<{object}>}
   */
  getUserInfoAsync() {
    return new Promise(
        (resolve, reject) => {
          wx.login({
            success({
              code
            }) {
              resolve(code)
            },
            fail() {
              reject('wx.login:fail')
            },
          })
        }
      )
      .then((code) => {
        return new Promise((resolve, reject) => {
          wx.getUserInfo({
            withCredentials: true,
            success({
              iv,
              encryptedData,
              userInfo
            }) {
              userStore.setData(USER_INFO, userInfo)
              resolve({
                code,
                iv,
                encryptedData,
                userInfo
              })
            },
            fail() {
              reject('wx.getUserInfo:fail')
            },
          })
        })
      })
      .catch((err) => {
        console.error('getUserInfoAsyncError:: ===')
        console.log(err)
      })
  },

  /**
   * 确保登陆
   * @param func {function}
   * @param invoke {boolean}f - 登录成功后是否执行
   * @returns {void}
   */
  ensureLogined(func, invoke = true) {
    if (!utils.isFunc(func)) throw new TypeError('func is not a function')
    // 1 是否已登录
    if (!this.getIsLogin()) {
      // 2 未登录，是否已授权
      this.getIsAuthAsync()
        .then(() => {
          // 3.1 已授权，获取用户信息
          console.log('登录已授权')
          this.getUserInfoAsync().then(() => {
            func(userStore.getData(USER_INFO))
          });
        })
        .catch(() => {
          // 3.2 未授权，跳转授权页
          console.log('登录未授权');
          func();
          //invoke && this.eventEmitter.once(EVENT_LOGIN, func)
        })
    } else {
      //已登录,跳转首页
      console.log('已登录');
      wx.reLaunch({ url: '/pages/orders/index/index'})
     // wx.reLaunch({ url: "/pages/account/register/step2/RegisterStep2?mobile=15108225651"})
      //func(userStore.getData(USER_INFO))
    }
  },

  /**
   * 微信登录 登录
   * @returns {Promise<{code: *, iv: *, encryptedData?: *}>}
   */
  loginByWeixinAsync(func) {
    wx.showToast({
      title: 'loading',
      icon: 'loading',
      duration: 10000
    });

    return this.getUserInfoAsync()
      .then(({
        code,
        iv,
        encryptedData
      }) => {
        return http.loginByWeixin({
          code,
          iv,
          encryptedData: encryptedData,
        }).then(({
          token
        }) => {
          wx.hideToast();
          this._data[TOKEN] = 'abc12345'; //98a38c56e95a92b9b9bbfe906d11ac26
          // 已登陆，设置登录状态
          this.setLoginStatus();
          if (utils.isFunc(func)) {
            func();
          }
        }).catch((err) => {
          wx.hideToast();
          console.log(err)
        })
      })
  },

  /**
   * 微信注册的登录
   * @returns {Promise<{code: *, iv: *, encryptedData?: *}>}
   */
  RegisterLoginByWeixinAsync(func) {
    wx.showToast({
      title: 'loading',
      icon: 'loading',
      duration: 10000
    });

    return this.getUserInfoAsync()
      .then(({
        code,
        iv,
        encryptedData
      }) => {
        return http.RegisterLoginByWeixin({
          code,
          iv,
          encryptedData: encryptedData,
        }).then(({
          token
        }) => {
          wx.hideToast();
          this._data[TOKEN] = 'abc12345'; //98a38c56e95a92b9b9bbfe906d11ac26
          // 已登陆，设置登录状态
          this.setLoginStatus();
          if (utils.isFunc(func)) {
            func();
          }
        }).catch((err) => {
          wx.hideToast();
          console.log(err)
        })
      })
  },

  loginByPhoneNumber(param, _this) {
    wx.showToast({
      title: 'loading',
      icon: 'loading',
      duration: 10000
    });

    return http.saveLogin(param)
      .then(({
        token
      }) => {
        wx.hideToast();
        this._data[TOKEN] = token;
        // 已登陆，设置登录状态
        this.setLoginStatus();
        //this.eventEmitter.emit(EVENT_LOGIN, userStore.getData(USER_INFO));
        utils.go("pages/orders/index/index", 4)
      }).catch((err) => {
        wx.hideToast();
        Toast.show(_this, 'info', err.message);
        console.log(err)
      })
  },

  /**
   * 设置登录状态
   * @private
   */
  setLoginStatus() {
    // 登录凭证和登录时间存储到本地
    wx.setStorageSync(TOKEN, this._data[TOKEN])
    wx.setStorageSync(LAST_LOGIN, Date.now())

    // 登录凭证和登录信息存储到 store
    userStore.setData({
      [TOKEN]: this._data[TOKEN]
    })

    http.$setHeader('token', this._data[TOKEN])
  },

  /**
   * 清除登录状态
   * @returns {void}
   */
  clearLoginStatus() {
    wx.removeStorageSync(TOKEN)
    wx.removeStorageSync(LAST_LOGIN)

    userStore.setData(TOKEN, '')
  },
}